### 验证 register 模块 用户所提交的表单
from django import forms
#from django.contrib.auth.models import User
from django.contrib.auth import get_user_model
from .models import CaptchaModel
User = get_user_model()
'''
用于 Django 表单验证类
主要用于处理用户注册时候提交的数据
'''
class RegisterForm(forms.Form):
    username = forms.CharField(max_length=20,min_length=5,error_messages={
        'required':'请输入用户名！',
        'max_length':'用户名长度在5-20之间',
        'min_length':'用户名长度在5-20之间'
    })
    email = forms.EmailField(error_messages={
        'required':'请输入邮箱！',
        'invalid':'请输入一个正确的邮箱!'
    })
    captcha = forms.CharField(max_length=6,min_length=6,error_messages={
        'required':'请输入验证码！',
        'max_length':'验证码长度为6',
        'min_length':'验证码长度为6'
    })
    password = forms.CharField(max_length=20,min_length=8,error_messages={
        'max_length': '密码长度在8-20之间',
        'min_length': '密码长度在8-20之间'
    })

    def clean_email(self):
        email = self.cleaned_data.get('email')
        #print(f"clean_email邮箱是:    {email}")
        result = User.objects.filter(email=email)
        #print(result.query)
        exists = result.exists()
        #print(f"User 表中的 email :{exists}")
        if exists:
            #raise forms.ValidationError('该邮箱已经被注册')
            print("该邮箱已经被注册")
        return email

    def clean_captcha(self):
        captcha = self.cleaned_data.get('captcha')
        #print(f"验证码：{captcha}")
        #email = self.cleaned_data.get('email')
        email = self.cleaned_data.get('email')
        #print(f"clean_captcha邮箱是:    {email}")

        ## 去库中查询 验证码是否存在
        ###filter 方法只能是 b=k=v
        ###
        result = CaptchaModel.objects.filter(email=email,captcha=captcha).first()

        #print(f"================{result}")

        ## if not 判断 值是否为 False
        if not result:
            raise forms.ValidationError('验证码和邮箱不匹配,请重试')
        ## 数据库中 存在验证码的 话  说明 用户尚未注册 先把库中的验证码删除
        result.delete() ## 确保验证码 只能使用一次
        return captcha  ## 返回 前端提交过来的验证码


## 验证登录
class LoginForm(forms.Form):
    email = forms.EmailField(error_messages={
        'required':'请输入邮箱！',
        'invalid':'请输入一个正确的邮箱!'
    })
    password = forms.CharField(max_length=20,min_length=8,error_messages={
        'max_length': '密码长度在8-20之间',
        'min_length': '密码长度在8-20之间'
    })
    remember = forms.IntegerField(required=False)
